package com.aztech.app;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;

import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.aztech.app.utils.SharedPreferencesUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.hyperai.hyperlpr3.HyperLPR3;
import com.hyperai.hyperlpr3.bean.HyperLPRParameter;
import com.hyperai.hyperlpr3.bean.Plate;
import com.just.agentweb.AgentWeb;

import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.WebViewClient;
import com.xuexiang.xupdate.XUpdate;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    public static final int REQUEST_CODE_SCAN_ONE = 1100;
    public static final int REQUEST_CODE_TAKE_PHOTO = 1200;
    public static final String DEFAULT_APP_ORIENTATION = "DEFAULT_APP_ORIENTATION";

    public static final String URL_APP_SERVER_IP = "10.10.8.35";
    public static final String URL_APP_DEFAULT_REDIRECT = "http://10.10.8.35:17000/Default.aspx?IsRedirect=Y";
    public static final String URL_APP_DEFAULT_NO_REDIRECT = "http://10.10.8.35:17000/Default.aspx";
    public static final String URL_APP_VERSION = "http://10.10.8.35:17000/Services/VersionService.ashx?App=AztechApp";

    public static String currImageFilePathTemp;

    private AgentWeb mAgentWeb;
    private RelativeLayout mMainLayout;
    private LinearLayout mLinearLayout;
    private AndroidInterface mAndroidInterface;

    private FloatingActionButton refreshButton;
    private FloatingActionButton stopButton;
    private FloatingActionButton homeButton;
    private FloatingActionButton visibleButton;
    private FloatingActionButton wifiButton;
    private FloatingActionButton screenButton;
    private FloatingActionButton keyboardButton;

//    private static boolean isShowKeyboard = false;
//    private static int currentOrientation = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始设定
        checkAppVersion();
        checkAppPermission();
        initFloatAction();
        initBroadcastReg();
        initHyperLPR3();

        //Load default page
        loadAgentWeb(URL_APP_DEFAULT_REDIRECT);

        //以当前屏幕方向，初始化应用方向
        //如果之前有设定过屏幕方向，则以设定方向为准
        setRequestedOrientation((int)SharedPreferencesUtils.getParam(this, DEFAULT_APP_ORIENTATION, getRequestedOrientation()));

    }

    /**
     * 加载指定网页
     * @param url
     */
    private void loadAgentWeb(String url) {
        if (mMainLayout == null)
            mMainLayout = ((RelativeLayout)findViewById(R.id.mainLayout));
        if (mLinearLayout == null)
            mLinearLayout = ((LinearLayout)findViewById(R.id.mainLinearLayout));

        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .createAgentWeb()
                .ready()
                .go(url);


        //记录Cookies，然后清除浏览器缓存
        String oldCookies = AgentWebConfig.getCookiesByUrl(URL_APP_DEFAULT_NO_REDIRECT);
        AgentWebConfig.clearDiskCache(this);
        AgentWebConfig.syncCookie(URL_APP_DEFAULT_NO_REDIRECT, oldCookies);

        //设置JS监听
        mAndroidInterface = new AndroidInterface(mAgentWeb,this);
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", mAndroidInterface);

    }


    /**
     * 注册应用消息推送接收
     * 本地推送需要在App隐藏状态下发出才能出现在顶部消息栏里
     * 所以除第三方推送平台外可能不太会使用推送消息
     */
    private void initBroadcastReg() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_EDIT);
        super.registerReceiver(new AzReceiver(), intentFilter);
    }

    /**
     * 第三方 HyperLPR3 车牌识别算法配置参数
     */
    private void initHyperLPR3() {
        // 车牌识别算法配置参数
        HyperLPRParameter parameter = new HyperLPRParameter()
                .setDetLevel(HyperLPR3.DETECT_LEVEL_LOW)
                .setMaxNum(1)
                .setRecConfidenceThreshold(0.85f);
        // 初始化(仅执行一次生效)
        HyperLPR3.getInstance().init(this, parameter);
    }

    /**
     * 初始化底部栏工具
     */
    private void initFloatAction() {
        refreshButton = (FloatingActionButton)findViewById(R.id.refreshButton);
        refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAgentWeb != null) {
                    mAgentWeb.getWebCreator().getWebView().clearCache(true);
                    mAgentWeb.getWebCreator().getWebView().loadUrl(mAgentWeb.getWebCreator().getWebView().getUrl());
                }
            }
        });

        homeButton = (FloatingActionButton)findViewById(R.id.homeButton);
        homeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAgentWeb != null)
                    mAgentWeb.getWebCreator().getWebView().loadUrl(URL_APP_DEFAULT_NO_REDIRECT);
            }
        });

        stopButton = (FloatingActionButton)findViewById(R.id.stopButton);
        stopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAgentWeb != null)
                    mAgentWeb.getWebCreator().getWebView().stopLoading();
            }
        });

        visibleButton = (FloatingActionButton)findViewById(R.id.visibleButton);
        visibleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int visible = refreshButton.getVisibility() == View.VISIBLE ? View.INVISIBLE : View.VISIBLE;
                refreshButton.setVisibility(visible);
                homeButton.setVisibility(visible);
                stopButton.setVisibility(visible);
                wifiButton.setVisibility((visible));
                screenButton.setVisibility((visible));
//                keyboardButton.setVisibility((visible));
            }
        });

        wifiButton = (FloatingActionButton)findViewById(R.id.wifiButton);
        wifiButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到WIFI设置页
                Intent intent=new Intent(MainActivity.this, WifiActivity.class);
                startActivity(intent);
            }
        });

        screenButton = (FloatingActionButton)findViewById(R.id.screenButton);
        screenButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                if (currentOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || currentOrientation == 6) {
//                    currentOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
//                } else if (currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
//                    currentOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
//                } else if (currentOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
//                    currentOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
//                } else if (currentOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
//                    currentOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
//                }
//                setRequestedOrientation(currentOrientation);

                //获取设置的配置信息
                Configuration mConfiguration = MainActivity.this.getResources().getConfiguration();
                //获取屏幕方向
                int ori = mConfiguration.orientation;
                if (ori == mConfiguration.ORIENTATION_LANDSCAPE) {
                    //如果横屏则强制竖屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    SharedPreferencesUtils.setParam(MainActivity.this, DEFAULT_APP_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else if (ori == mConfiguration.ORIENTATION_PORTRAIT) {
                    //如果竖屏则强制横屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    SharedPreferencesUtils.setParam(MainActivity.this, DEFAULT_APP_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
            }
        });

        keyboardButton = (FloatingActionButton)findViewById(R.id.keyboardButton);
        keyboardButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                //imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

                //mAgentWeb.getWebCreator().getWebView().setOnTouchListener(new View.OnTouchListener() {
                //    @Override
                //    public boolean onTouch(View v, MotionEvent event) {
                //        return false;
                //    }
                //});

                //getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                //getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

//                if (isShowKeyboard) {
//                    isShowKeyboard = false;
//                    Toast toast=Toast.makeText(MainActivity.this, "Close Keyboard!", Toast.LENGTH_SHORT);
//                    toast.show();
//                } else {
//                    isShowKeyboard = true;
//                    Toast toast=Toast.makeText(MainActivity.this, "Open Keyboard!", Toast.LENGTH_SHORT);
//                    toast.show();
//                }


//                if (mMainLayout.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
//                    mAgentWeb.getWebCreator().getWebView().setFocusable(true);
//                    mAgentWeb.getWebCreator().getWebView().setFocusableInTouchMode(true);
//                    mMainLayout.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
//                    Toast toast=Toast.makeText(MainActivity.this, "Open Keyboard!", Toast.LENGTH_SHORT);
//                    toast.show();
//
//                } else {
//                    mAgentWeb.getWebCreator().getWebView().setFocusable(false);
//                    mAgentWeb.getWebCreator().getWebView().setFocusableInTouchMode(true);
//                    mMainLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
//                    Toast toast=Toast.makeText(MainActivity.this, "Close Keyboard!", Toast.LENGTH_SHORT);
//                    toast.show();
//                }

            }
        });
    }

    /**
     * 获取App版本
     * 使用第三方升级框架XUpdate
     * 参考：https://github.com/xuexiangjys/XUpdate
     */
    private void checkAppVersion() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                XUpdate.newBuild(MainActivity.this)
                        .updateUrl(URL_APP_VERSION)
                        .update();
                Looper.loop();
            }
        }).start();

    }

    /**
     * 动态判断权限
     * 直接使用华为HMS API中权限检查
     */
    private void checkAppPermission() {
        String[] permissions = new String[] {
                Manifest.permission.INTERNET,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CAMERA
        };
        //指定Code可以用于在onRequestPermission回调时判断获取某一权限后指定处理逻辑，如有需要可针对某一权限单独设置
        ActivityCompat.requestPermissions(this,permissions, 0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mAgentWeb.back()) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        try {
            if (resultCode == RESULT_OK) {
                //华为HMS扫描二维码回调方法
                if (requestCode == REQUEST_CODE_SCAN_ONE) {
                    HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
                    if (obj != null) {
                        mAndroidInterface.callbackJsFunction(obj.getOriginalValue());
                        return;
                    }
                }

                //摄像头或扫描页面跳转回调方法
                if (requestCode == REQUEST_CODE_TAKE_PHOTO) {
                    File imageFile = new File(currImageFilePathTemp);
                    Uri imageUri;
                    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M){
                        imageUri = Uri.fromFile(imageFile);
                    }else{
                        imageUri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".provider", imageFile);
                    }

                    // 使用Bitmap作为图片参数进行车牌识别
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
                    Plate[] plates =  HyperLPR3.getInstance().plateRecognition(bitmap, HyperLPR3.CAMERA_ROTATION_0, HyperLPR3.STREAM_BGRA);
                    for (Plate plate: plates) {
                        // 打印检测到的车牌号
                        mAndroidInterface.callbackJsFunction(plate.getCode());
                        return;
                    }
                    mAndroidInterface.callbackJsFunction("Not found any license plate.");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 启用相机拍照，用于车牌识别
     */
    protected void showHyperLPRCamera() {
        //系统常量， 启动相机的关键
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //定义照片保存路径
        File imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (!imagePath.exists()) {
            imagePath.mkdir();
        }

        String fileName = "aztemp.jpg";
        File imageFile = new File(imagePath, fileName);
        Uri imageUri;

        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M){
            imageUri = Uri.fromFile(imageFile);
        }else{
            /**
             * 7.0 调用系统相机拍照不再允许使用Uri方式，应该替换为FileProvider
             * 并且这样可以解决MIUI系统上拍照返回size为0的情况
             */
            imageUri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".provider", imageFile);
        }

        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        // 参数常量为自定义的REQUEST_CODE_TAKE_PHOTO, 在取返回结果时有用
        startActivityForResult(openCameraIntent, REQUEST_CODE_TAKE_PHOTO);
        //设置临时全局照片名称
        currImageFilePathTemp = imageFile.getAbsolutePath();
    }
}

/**
 * 注册AgentWeb中JS事件的类
 */
class AndroidInterface {
    private AgentWeb agent;
    private Context context;
    private String callbackFunction;

    public AndroidInterface(AgentWeb agent, Context context) {
        this.agent = agent;
        this.context = context;
    }

    /**
     * 跳转到火狐内核页面并访问指定URL
     * @param targetURL
     */
    @JavascriptInterface
    public void goGeckoView(String targetURL) {
        Intent intent = new Intent(this.context, WebActivity.class);
        intent.putExtra("Website", targetURL);
        this.context.startActivity(intent);
    }

    /**
     * 打开扫码工具
     * @param callback
     */
    @JavascriptInterface
    public void showScanKit(String callback) {
        this.callbackFunction = callback;
        ScanUtil.startScan((Activity)this.context, MainActivity.REQUEST_CODE_SCAN_ONE, null);
    }

    /**
     * 拍照识别车牌
     * @param callback
     */
    @JavascriptInterface
    public void showHyperLPR3(String callback) {
        this.callbackFunction = callback;
        ((MainActivity)this.context).showHyperLPRCamera();
    }

    /**
     * 播放提示音
     * @param isAlarm
     */
    @JavascriptInterface
    public void sendBroadcastMsg(boolean isAlarm, String callback) {
        //播放系统自带提示音，闹铃为长提醒，信息声为短提醒
        int typeMusic = isAlarm ? RingtoneManager.TYPE_ALARM : RingtoneManager.TYPE_NOTIFICATION;
        Uri uri = RingtoneManager.getDefaultUri(typeMusic);
        Ringtone rt = RingtoneManager.getRingtone(this.context.getApplicationContext(), uri);
        rt.play();


        this.callbackFunction = callback;
        callbackJsFunction("Success");
    }

    /**
     * 发送系统顶部栏消息
     * @param msg
     */
    @JavascriptInterface
    public void sendNotification(String msg) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelID = "1";
            String channelName = "AZTECH_CHANNEL";

            //设置点击通知跳转活动
            Intent intent = new Intent(context, MainActivity.class);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setAction(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            PendingIntent pi = PendingIntent.getActivity(context,0 ,intent ,0 );

            Notification.Builder builder = new Notification.Builder(context, channelID);
            builder.setSmallIcon(R.drawable.aztech);
            builder.setCategory(Notification.CATEGORY_MESSAGE);
            builder.setAutoCancel(true); //自动消失
            builder.setWhen(System.currentTimeMillis());
            builder.setContentTitle("Aztech Notification");
            builder.setContentText(msg);
            builder.setContentIntent(pi);

            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(channelID,channelName, NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true); //是否在桌面icon右上角展示小红点
            channel.setLightColor(Color.RED); //小红点颜色
            channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
            manager.createNotificationChannel(channel);
            manager.notify((int)Math.round(Math.random()*100), builder.build());
        }
    }

    /**
     * 手动升级应用
     */
    @JavascriptInterface
    public void upgradVersion() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                XUpdate.newBuild(context)
                        .updateUrl(MainActivity.URL_APP_VERSION)
                        .update();
            }
        }).start();
    }




    public void callbackJsFunction(String... param) {
        agent.getJsAccessEntrace().quickCallJs(callbackFunction, param);
    }

}